//
//  LXTitleView.swift
//  LXPageView
//
//  Created by seven on 2017/11/9.
//  Copyright © 2017年 seven. All rights reserved.
//

import UIKit

protocol LXTitleViewDelegete: class {
    func titleView(_ titleView: LXTitleView, targetIndex: Int)
}

class LXTitleView: UIView {
    
    weak var delegete: LXTitleViewDelegete?
    private var titles: [String]
    private var style: LXTitleStyle
    private lazy var titleLabels: [UILabel] = [UILabel]()
    private lazy var currentIndex: Int = 0
    
    private lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView(frame: self.bounds)
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.scrollsToTop = false
        return scrollView
    }()
    
    private lazy var indicatorLine: UIView = {
        let indicatorLine = UIView()
        indicatorLine.backgroundColor = self.style.indecatorLineColor
        indicatorLine.frame.size.height = self.style.indicatorLineHeight
        indicatorLine.frame.origin.y = self.bounds.height - style.indicatorLineHeight
        return indicatorLine
    }()
    
    init(frame: CGRect, titles: [String], style: LXTitleStyle) {
        self.titles = titles
        self.style = style
        
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension LXTitleView{
    private func setupUI() {
        //1.加入scrollview
        addSubview(scrollView)
        //2.加入titleLabel
        setupTitleLabel()
        //3.设置titlLabel的frame
        setupTitleLabelsFrame()
        //4.添加滚动条
        if style.isShowIndicatorLine{
            scrollView.addSubview(indicatorLine)
        }
        
    }
    private func setupTitleLabel(){
        titles.enumerated().forEach { (i,title) in
            let titleLabel = UILabel()
            titleLabel.text = title
            titleLabel.textColor = .black
            titleLabel.font = UIFont.systemFont(ofSize: style.fontSzie)
            titleLabel.textAlignment = .center
            titleLabel.tag = i
            titleLabel.textColor = i == 0 ? style.selectColor : style.normalColor
            scrollView.addSubview(titleLabel)
            titleLabels.append(titleLabel)
            
            let tap = UITapGestureRecognizer(target: self, action: #selector(titleLableClick(_:)))
            titleLabel.addGestureRecognizer(tap)
            titleLabel.isUserInteractionEnabled = true
        }
    }
    private func setupTitleLabelsFrame(){
        let count = titles.count
        titleLabels.enumerated().forEach { (i,label) in
            var w: CGFloat = 0
            let h: CGFloat = bounds.height
            var x: CGFloat = 0
            let y: CGFloat = 0
            if style.isScrollEnable{//可以滚动
                w = titles[i].boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 0), options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font : label.font], context: nil).size.width
                if i == 0 {
                    x = style.itemMargin * 0.5
                    if style.isShowIndicatorLine {
                        indicatorLine.frame.origin.x = x
                        indicatorLine.frame.size.width = w
                    }
                } else {
                    x = titleLabels[i - 1].frame.maxX + style.itemMargin
                }
            } else {//不可以滚动
                w = bounds.width / CGFloat(count)
                x = w * CGFloat(i)
                var indicatorLineW: CGFloat = 0
                if style.isIndicatorLineWidthEqualToTitle {
                    indicatorLineW = titles[i].boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 0), options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font : label.font], context: nil).size.width
                } else {
                    indicatorLineW = w
                }
                if i == 0 && style.isShowIndicatorLine{
                    indicatorLine.frame.size.width = indicatorLineW
//                    indicatorLine.frame.origin.x = x
                    indicatorLine.center.x = w / 2
                }
            }
            
            label.frame = CGRect(x: x, y: y, width: w, height: h)
        }
        
        scrollView.contentSize = style.isScrollEnable ? CGSize(width: titleLabels.last!.frame.maxX + style.itemMargin * 0.5, height: 0) : CGSize.zero
    }
}

//监听事件
extension LXTitleView{
    @objc private func titleLableClick(_ tap: UITapGestureRecognizer){
        //取出点击的label和上一个label
        let targetLabel = tap.view as! UILabel
        //调整titleLabel位置
        adjustTitleLabel(targetIndex: targetLabel.tag)
        //调整指示线
        if style.isShowIndicatorLine {
            UIView.animate(withDuration: 0.15, animations: {
                if self.style.isIndicatorLineWidthEqualToTitle {
                    self.indicatorLine.frame.size.width = targetLabel.text!.boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 0), options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font : targetLabel.font], context: nil).size.width
                    self.indicatorLine.center.x = targetLabel.center.x
                } else {
                    self.indicatorLine.frame.origin.x = targetLabel.frame.origin.x
                    self.indicatorLine.frame.size.width = targetLabel.frame.size.width
                }
            })
        }
        //通知contentView进行切换
        delegete?.titleView(self, targetIndex: currentIndex)
        
    }
    
    func adjustTitleLabel(targetIndex: Int){
        if targetIndex == currentIndex {return}
        let targetLabel = titleLabels[targetIndex]
        let frontLabel = titleLabels[currentIndex]
        
        frontLabel.textColor = style.normalColor
        targetLabel.textColor = style.selectColor
        //记录下标值
        currentIndex = targetIndex
        
        //调整位置
        if style.isScrollEnable{//可以滚动则选中居中
            var offsetX = targetLabel.center.x - scrollView.bounds.width * 0.5
            if offsetX < 0 {
                offsetX = 0
            }
            if offsetX > (scrollView.contentSize.width - scrollView.bounds.width){
                offsetX = scrollView.contentSize.width - scrollView.bounds.width
            }
            scrollView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
        }
        
        if style.isShowIndicatorLine {
            UIView.animate(withDuration: 0.15, animations: {
                if self.style.isIndicatorLineWidthEqualToTitle {
                    self.indicatorLine.frame.size.width = self.titles[targetIndex].boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 0), options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font : self.titleLabels[targetIndex].font], context: nil).size.width
                    self.indicatorLine.center.x = targetLabel.center.x
                } else {
                    self.indicatorLine.frame.origin.x = targetLabel.frame.origin.x
                    self.indicatorLine.frame.size.width = targetLabel.frame.size.width
                }
            })
        }
    }
}

//MARK:- contentView的代理
extension LXTitleView: LXContentViewDelegete{
    func contentView(_ contentView: LXContentView, targetIndex: Int) {
        adjustTitleLabel(targetIndex: targetIndex)
    }
    func contentView(_ contentView: LXContentView, sourceIndex: Int, targetIndex: Int, progress: CGFloat) {
        //取出两个label
        if targetIndex == currentIndex {return}
        let frontLabel = titleLabels[currentIndex]
        let targetLabel = titleLabels[targetIndex]
        //颜色渐变
//        let deltaRGB = UIColor.getRGBDelta(firstColor: style.selectColor, secondColor: style.normalColor)
//        let selectedRGB = style.selectColor.getRGB()
//        let normalRGB = style.normalColor.getRGB()
//        targetLabel.textColor = UIColor(R: normalRGB.0 + deltaRGB.0 * progress, G: normalRGB.1 + deltaRGB.1 * progress, B: normalRGB.2 + deltaRGB.2 * progress)
//        frontLabel.textColor = UIColor(R: selectedRGB.0 + deltaRGB.0 * progress, G: selectedRGB.1 + deltaRGB.1 * progress, B: selectedRGB.2 + deltaRGB.2 * progress)
//        let sourceLabel = titleLabels[sourceIndex]
        let deltaX = targetLabel.frame.origin.x - frontLabel.frame.origin.x
        let deltaW = targetLabel.frame.width + style.itemMargin
        if style.isIndicatorLineFlexible {
            if deltaX >= 0{
                indicatorLine.frame.size.width = frontLabel.frame.width + deltaW * progress
                indicatorLine.frame.origin.x = frontLabel.frame.origin.x
            }else{
                indicatorLine.frame.size.width = frontLabel.frame.width + deltaW * progress
                indicatorLine.frame.origin.x = frontLabel.frame.origin.x - deltaW * progress
            }
            
        }
        
    }
    
}
